/**
 * @FileName: HttpUtil.java
 * @Author
 * @Description:
 * @Date 2016年1月5日 下午2:22:42
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;

import javax.net.ssl.HttpsURLConnection;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.net.MediaType;

import cn.hpclub.server.constant.ClientApiConstant;

public class HttpUtil{
    public static final String  HTTP_ERROR = "Error:getHttpByPostBody exception";
    private static final Logger logger     = LoggerFactory.getLogger(HttpUtil.class);

    public static JSONObject setResponseObj(int code, String msg, Object data){
        JSONObject rjson = new JSONObject();

        rjson.put(ClientApiConstant.Key.RESULT_CODE, code);
        rjson.put(ClientApiConstant.Key.MESSAGE, msg);

        // if(!"".equals(data)){
        rjson.put(ClientApiConstant.Key.DATA, data);
        // }

        return rjson;
    }

    public static String getHttpByPost(String actionName, HashMap<String, Object> value) throws IOException{
        logger.warn("actionName=" + actionName);
        HttpURLConnection connect = (HttpURLConnection)new java.net.URL(actionName).openConnection();
        connect.setRequestMethod("POST");
        connect.setDoOutput(true);
        connect.setUseCaches(false);
        connect.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
        connect.setConnectTimeout(15000);
        connect.setReadTimeout(15000);

        String params = "";

        Iterator<String> iterator = value.keySet().iterator();
        while(iterator.hasNext()){
            String key = iterator.next().toString();
            params += key + "=" + URLEncoder.encode(value.get(key).toString(), "UTF8") + "&";
        }
        if(params.length() > 0){
            params = params.substring(0, params.length() - 1);
        }
        // logger.warn("params=" + params);
        PrintWriter out = new PrintWriter(connect.getOutputStream());
        out.print(params);
        out.flush();
        out.close();

        connect.connect();

        logger.warn("request dpr interface :: result code=" + connect.getResponseCode());

        if(connect.getResponseCode() == 200){
            InputStream is = connect.getInputStream();
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            int ch;
            while((ch = is.read()) != -1){
                bytestream.write(ch);
            }
            is.close();
            connect.disconnect();
            byte[] result = bytestream.toByteArray();
            // logger.info("result=" + new String(result));
            // logger.warn("request success!!!!!");

            return new String(result);
        } else{
            // logger.info("result code=" + connect.getResponseCode());
            // logger.warn("request fail!!!!!");
            return null;
        }
    }

    public static String getHttpByGet(String actionName, HashMap<String, Object> value) throws Exception{
        try{
            // logger.warn("actionName=" + actionName);
            String params = "";
            // value.put(Contents.HttpKey.AppKey, Contents.APPKEY);
            // value.put(Contents.HttpKey.TimesSamp, MUtil.getTimeStamp());
            // value.put(Contents.HttpKey.Digest, toDigest());
            // value.put(Contents.HttpKey.Token, Contents.TOKEN);
            int length = value.entrySet().size();
            int i = 0;
            for(Iterator<String> iterator = value.keySet().iterator(); iterator.hasNext();){
                i++;
                String key = iterator.next().toString();
                params += key + "=" + URLEncoder.encode(value.get(key).toString(), "UTF8");
                if(i != length){
                    params = params + "&";
                }
            }

            String url = actionName + "?" + params;

            logger.warn("action url =" + url);

            HttpURLConnection connect = (HttpURLConnection)new java.net.URL(url).openConnection();
            connect.setRequestMethod("GET");
            connect.setDoOutput(true);
            connect.setUseCaches(false);
            connect.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            connect.setConnectTimeout(15000);
            connect.setReadTimeout(15000);

            connect.connect();

            logger.warn("request third api interface :: result code=" + connect.getResponseCode());

            if(connect.getResponseCode() == 200){
                InputStream is = connect.getInputStream();
                ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                int ch;
                while((ch = is.read()) != -1){
                    bytestream.write(ch);
                }
                is.close();
                connect.disconnect();
                byte[] result = bytestream.toByteArray();

                logger.warn("request success!!!!!");
                // logger.info("result=" + new String(result));
                // JSONObject jo = new JSONObject(new String(result));
                // logger.warn("result resCode=" + jo);
                // if(!actionName.equals(Contents.Url.VerifyAccount) && flag){
                // if(loginBackground()){
                // return getHttpByGet(actionName, value, false);
                // }
                // }
                return new String(result);

            } else{
                logger.warn("request fail!!!!!");
                return null;
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 新的http请求请调用syncPostJsonBody
     * 
     * @param url
     * @param data
     * @return
     */
    @Deprecated
    public static String getHttpByPostBody(String url, String data){

        try{
            HttpURLConnection connect = (HttpURLConnection)new java.net.URL(url).openConnection();
            connect.setRequestMethod("POST");
            connect.setDoOutput(true);
            connect.setUseCaches(false);
            connect.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            connect.setConnectTimeout(15000);
            connect.setReadTimeout(15000);

            PrintWriter out = new PrintWriter(connect.getOutputStream());
            out.print(data);
            out.flush();
            out.close();
            connect.connect();
            logger.info("getResponseCode:" + connect.getResponseCode());
            if(connect.getResponseCode() == 200){
                InputStream is = connect.getInputStream();
                ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                int ch;
                while((ch = is.read()) != -1){
                    bytestream.write(ch);
                }
                is.close();
                connect.disconnect();
                byte[] result = bytestream.toByteArray();
                return new String(result);
            } else{
                return HTTP_ERROR;
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return HTTP_ERROR;
    }

    /**
     * @Title: syncPostJsonBody
     * @Description:通过json格式body发送HTTP POST请求， 主要用于REST RPC类的请求。
     * @param url
     * @param data
     * @param timeout TODO
     * @return
     * @throws IOException
     *             String
     */
    public static String syncPostJsonBody(String url, MediaType mediaType, String data, int timeout) throws IOException{

        try{
            HttpURLConnection connect = (HttpURLConnection)new java.net.URL(url).openConnection();
            connect.setRequestMethod("POST");
            connect.setDoOutput(true);
            connect.setUseCaches(false);
            connect.setRequestProperty("Content-type", mediaType.toString());
            connect.setConnectTimeout(timeout); // 开户接口admin和RPC都read
                                              // timeout。业务层加长超时时间。
            connect.setReadTimeout(timeout);

            PrintWriter out = new PrintWriter(connect.getOutputStream());
            out.print(data);
            out.flush();
            out.close();
            connect.connect();
            logger.debug("media type:" + mediaType.toString());
            logger.debug("getResponseCode:" + connect.getResponseCode());
            if(connect.getResponseCode() == 200){
                InputStream is = connect.getInputStream();
                ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                int ch;
                while((ch = is.read()) != -1){
                    bytestream.write(ch);
                }
                is.close();
                connect.disconnect();
                byte[] result = bytestream.toByteArray();
                return new String(result);
            } else{
                throw new Exception("HTTP请求响应：" + connect.getResponseCode());
            }
        }
        catch(Exception e){
            e.printStackTrace();
            logger.error("http post exception:" + e.getMessage());
            throw new IOException("" + e.getMessage());
        }
    }

    /**
     * 发送HTTP GET请求， 主要用于REST的请求。
     * 
     * @param actionName
     * @param mediaType
     * @param value
     * @return
     * @throws Exception
     */
    public static String syncGetParameterMap(String actionName, MediaType mediaType, HashMap<String, Object> value)
            throws Exception{
        try{
            String params = "";
            int length = value.entrySet().size();
            int i = 0;
            for(Iterator<String> iterator = value.keySet().iterator(); iterator.hasNext();){
                i++;
                String key = iterator.next().toString();
                params += key + "=" + URLEncoder.encode(value.get(key).toString(), "UTF8");
                if(i != length){
                    params = params + "&";
                }
            }
            String url = actionName + "?" + params;
            logger.warn("action url =" + url);
            HttpURLConnection connect = (HttpURLConnection)new java.net.URL(url).openConnection();
            connect.setRequestMethod("GET");
            connect.setDoOutput(true);
            connect.setUseCaches(false);
            connect.setRequestProperty("Content-type", mediaType.toString());
            connect.setConnectTimeout(15000);
            connect.setReadTimeout(15000);
            connect.connect();
            logger.warn("request third api interface :: result code=" + connect.getResponseCode());
            if(connect.getResponseCode() == 200){
                InputStream is = connect.getInputStream();
                ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                int ch;
                while((ch = is.read()) != -1){
                    bytestream.write(ch);
                }
                is.close();
                connect.disconnect();
                byte[] result = bytestream.toByteArray();

                logger.warn("request success!!!!!");
                return new String(result);
            } else{
                logger.warn("request fail!!!!!");
                return null;
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    
    public static String getHttpsBody(String actionName, String body) throws IOException{
        logger.debug("actionName=" + actionName);
        HttpsURLConnection connect = (HttpsURLConnection)new java.net.URL(actionName).openConnection();
        connect.setRequestMethod("POST");
        connect.setDoOutput(true);
        connect.setUseCaches(false);
        connect.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
        connect.setConnectTimeout(15000);
        connect.setReadTimeout(15000);

        PrintWriter out = new PrintWriter(connect.getOutputStream());
        out.print(body);
        out.flush();
        out.close();

        connect.connect();
        if(connect.getResponseCode() == 200){
            InputStream is = connect.getInputStream();
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            int ch;
            while((ch = is.read()) != -1){
                bytestream.write(ch);
            }
            is.close();
            connect.disconnect();
            byte[] result = bytestream.toByteArray();
            logger.debug("result=" + new String(result));
            return new String(result);
        } else{
            logger.error("result code=" + connect.getResponseCode());
            return null;
        }
    }
}
